<?php

namespace app\api\controller;

use addons\douyin\controller\Vod;
use app\common\controller\AliVod;
use think\Log;

class Video
{
    public function aliComposeComplete()
    {
        $resData = json_decode(file_get_contents('php://input'), 1);
        $data = [];
        $data['EventType'] = 'ComposeMediaComplete';

        if (isset($resData['Status']) && $resData['Status'] === 'success') {
            $data['ComposeMediaCompleteEvent']['TaskId'] = $resData['MediaId'];
        } else {
            Log::error('ali视频合成回调数据错误：' . json_encode($resData));
            return;
        }

        if (isset($resData['Status']) && $resData['Status'] === 'success') {
            try {
                $mediaPlayRes = (new AliVod)->getPlayInfo($resData['MediaId']);
            } catch (\Exception $e) {
                Log::error('ali视频合成错误：' . $e->getMessage());
                return;
            }
            if (empty($mediaPlayRes->body->playInfoList->playInfo)) {
                Log::error('ali视频合成playInfo错误：' . json_encode($mediaPlayRes));
                return;
            }
            $playInfo = json_decode(json_encode($mediaPlayRes), 1);
            if (empty($fileUrl = $playInfo['body']['playInfoList']['playInfo'][0]['playURL'])) {
                Log::error('ali视频合成playURL错误：' . json_encode($playInfo));
                return;
            }

            $data['ComposeMediaCompleteEvent']['Status'] = 'FINISH';
            $data['ComposeMediaCompleteEvent']['Output']['FileId'] = $playInfo['body']['videoBase']['videoId'];
            $data['ComposeMediaCompleteEvent']['Output']['FileUrl'] = $fileUrl;
        } else {
            $data['ComposeMediaCompleteEvent']['Status'] = 'fail';
            $data['ComposeMediaCompleteEvent']['Message'] = $resData['ErrorMessage'];
        }

        (new Vod)->notify($data);
    }

}
